'use client';

import { useEffect } from 'react';

export default function ErrorBoundary({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    const handleError = (event: ErrorEvent) => {
      console.error('全局错误:', event.error);
      
      // 特别处理JSON解析错误
      if (event.error instanceof SyntaxError && event.error.message.includes('Unexpected token')) {
        console.error('JSON解析错误，可能是服务器返回了HTML而不是JSON');
        console.error('错误详情:', event.error);
        console.error('错误位置:', event.filename, ':', event.lineno);
      }
    };

    const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
      console.error('未处理的Promise拒绝:', event.reason);
      
      // 处理fetch错误
      if (event.reason && typeof event.reason === 'object' && 'message' in event.reason) {
        const error = event.reason as Error;
        if (error.message.includes('Unexpected token') || error.message.includes('<!DOCTYPE')) {
          console.error('API响应错误，服务器可能返回了HTML而不是JSON');
        }
      }
    };

    window.addEventListener('error', handleError);
    window.addEventListener('unhandledrejection', handleUnhandledRejection);

    return () => {
      window.removeEventListener('error', handleError);
      window.removeEventListener('unhandledrejection', handleUnhandledRejection);
    };
  }, []);

  return <>{children}</>;
} 